package com.jvm.classloader;

import java.io.*;

/**
 * 自定义类加载器
 */
public class MyTest16 extends ClassLoader{

    private String classLoaderName = "";

    private String path;

    public static final String fileExtension = ".class";

    public void setPath(String path) {
        this.path = path;
    }

    public MyTest16(String classLoaderName){
        super();//将系统类加载器当作该类加载器的父加载器
        this.classLoaderName = classLoaderName;
    }

    public MyTest16(ClassLoader parent, String classLoaderName){
        super(parent);//显示指定该类加载器的父加载器
        this.classLoaderName = classLoaderName;
    }

    /**
     * 这个方法是当你指定java.system.class.loader这个系统变量时
     * （用于改变默认的系统类加载器）需要指定双亲的方法。
     * @param parent
     */
    public MyTest16(ClassLoader parent){
        super(parent);
    }

    @Override
    public String toString() {
        return "MyTest16{" +
                "classLoaderName='" + classLoaderName + '\'' +
                '}';
    }

    private byte[] loadClassData(String className){
        InputStream is = null;
        byte[] data = null;
        ByteArrayOutputStream baos = null;

        className = className.replace(".","\\");

        try{

            is = new FileInputStream(new File(this.path + className + fileExtension));
            baos = new ByteArrayOutputStream();

            int ch = 0;

            while (-1 != (ch = is.read())){
                baos.write(ch);
            }

            data = baos.toByteArray();

        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            try {
                is.close();
                baos.close();
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
        return data;
    }

    @Override
    protected Class<?> findClass(String className) throws ClassNotFoundException {
        System.out.println("findClass invoked:" + className);
        System.out.println("class loader name:" + this.classLoaderName);
        byte[] b = loadClassData(className);
        return defineClass(className, b, 0, b.length);
    }

    public static void main(String[] args) throws Exception {
        MyTest16 loader1 = new MyTest16("loader1");
        loader1.setPath("E:\\jvm_lecture\\jvm_lecture\\out\\production\\jvm_lecture\\");
        test(loader1);

        MyTest16 loader2 = new MyTest16(loader1,"loader1");
        loader2.setPath("E:\\jvm_lecture\\jvm_lecture\\out\\production\\jvm_lecture\\");
        test(loader2);
    }

    public static void test(ClassLoader classLoader) throws Exception {
        Class<?> clazz = classLoader.loadClass("com.jvm.classloader.MyTest1");
        Object obj = clazz.newInstance();

        System.out.println(obj);
        System.out.println(obj.getClass().getClassLoader());
    }
}
